<template>
  <div class="app-container">
    <el-tabs v-model="activeName">
      <el-tab-pane label="单个扫码生成" name="oneCreate">
        <el-form label-width="100px" :inline="true" ref="form" :model="form" :rules="rules" v-if="'oneCreate' == activeName">
          <el-form-item label="工艺路线" prop="routeId">
            <el-select v-model="form.routeId" placeholder="请选择工艺路线" clearable filterable size="small">
              <el-option v-for="item in routeOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId">
                <span style="float: left">{{ item.routeName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.routeId }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工单号" prop="productionOrder">
            <el-select v-model="batchSaveList[0].productionOrder" placeholder="请选择工单号" @change="productionOrderChange" clearable filterable size="small">
              <el-option v-for="item in workOrderOptions" :key="item.id" :label="item.productionOrder" :value="item.productionOrder"></el-option>
            </el-select>
            <b>工单剩余数量：<span style="color: red;">{{ workOrderRestQty }}</span></b>
          </el-form-item>
          <el-form-item label="效率" prop="efficiency">
            <el-input v-model="batchSaveList[0].efficiency" placeholder="请输入效率" clearable size="small" />
          </el-form-item>
          <!-- <el-form-item label="颜色" prop="color">
            <el-input v-model="batchSaveList[0].color" placeholder="请输入颜色" clearable size="small" />
          </el-form-item> -->
          <el-form-item label="开压" prop="pressure">
            <el-input v-model="batchSaveList[0].pressure" placeholder="请输入开压" clearable size="small" />
          </el-form-item>
          <el-form-item label="功率" prop="power">
            <el-input v-model="batchSaveList[0].power" placeholder="请输入功率" clearable size="small" />
          </el-form-item>
          <!-- <el-form-item label="等级" prop="grade">
            <el-input v-model="batchSaveList[0].grade" placeholder="请输入等级" clearable size="small" />
          </el-form-item> -->
          <el-form-item label="小包数量" prop="packQty">
            <el-input v-model="form.packQty" type="number" placeholder="请输入小包数量" clearable size="small" />
          </el-form-item>
          <el-form-item label="入包时间" prop="packTime">
            <el-date-picker v-model="daterangePackTime" style="width: 360px" value-format="yyyy/MM/dd HH:mm" type="datetimerange" range-separator="-" start-placeholder="最小值" end-placeholder="最大值" size="small"></el-date-picker>
          </el-form-item>
          <el-form-item label="入库批次" prop="inBatchNo">
            <el-input v-model="batchSaveList[0].inBatchNo" style="width: 18.75rem;"  placeholder="请输入入库批次" clearable size="small" />
          </el-form-item>
          <el-form-item label="托号" prop="palletNo">
            <el-input v-model="batchSaveList[0].palletNo" style="width: 18.75rem;"  placeholder="请输入托号" clearable size="small" />
          </el-form-item>
          <el-form-item label="箱号" prop="boxNo">
            <el-input v-model="batchSaveList[0].boxNo" style="width: 18.75rem;"  placeholder="请输入箱号" clearable size="small" />
          </el-form-item>
          <el-form-item label="小包号" prop="packName">
            <!-- <el-input type="textarea" v-model="batchSaveList[0].packName" style="width: 18.75rem;" placeholder="请输入小包号，多个小包多行" @input="handlePackNameConvert" clearable size="small" @keyup.enter.native="submitBatchSaveForm" /> -->
            <el-input type="textarea" v-model="batchSaveList[0].packName"
            style="width: 18.75rem; "    :autosize="{ minRows: 2, maxRows: 4}"  placeholder="请输入小包号，多个小包多行"  clearable size="lage"  />
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitBatchSaveForm" size="mini" v-loading.fullscreen.lock="fullscreenLoading">生 成</el-button>
          </el-form-item>

        </el-form>
      </el-tab-pane>
      <el-tab-pane label="批量导入生成" name="batchCreate">
        <el-form label-width="100px" :inline="true" ref="form" :model="form" :rules="rules" v-if="'batchCreate' == activeName">
          <el-form-item label="工艺路线" prop="routeId">
            <el-select v-model="form.routeId" placeholder="请选择工艺路线" clearable filterable size="small">
              <el-option v-for="item in routeOptions" :key="item.routeId" :label="item.routeName" :value="item.routeId">
                <span style="float: left">{{ item.routeName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.routeId }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="入包时间" prop="packTime">
            <el-date-picker v-model="daterangePackTime" style="width: 360px" value-format="yyyy/MM/dd HH:mm" type="datetimerange" range-separator="-" start-placeholder="最小值" end-placeholder="最大值" size="small"></el-date-picker>
          </el-form-item>
          <el-form-item label="小包数量" prop="packQty">
            <el-input v-model="form.packQty" type="number" placeholder="请输入小包数量" clearable size="small" />
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="submitBatchSaveForm" size="mini" v-loading.fullscreen.lock="fullscreenLoading">生 成</el-button>
          </el-form-item>
          <el-divider content-position="center">小包明细</el-divider>
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="warning" icon="el-icon-download" size="mini" @click="downloadBatchSaveTemplate">下载模板</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleClearBatchSave">清空</el-button>
            </el-col>
          </el-row>
          <div v-on:paste="handlePasteBatchSave">
            <el-table size="mini" :data="batchSaveList" :row-class-name="rowPumpInfoIndex" ref="HrEqpBase">
              <el-table-column label="序号" align="center" prop="index"/>
              <el-table-column label="工单号" prop="productionOrder"></el-table-column>
              <el-table-column label="入库批次" prop="inBatchNo"></el-table-column>
              <el-table-column label="托号" prop="palletNo"></el-table-column>
              <el-table-column label="箱号" prop="boxNo"></el-table-column>
              <el-table-column label="效率" prop="efficiency"></el-table-column>
              <!-- <el-table-column label="颜色" prop="color"></el-table-column> -->
              <el-table-column label="开压" prop="pressure"></el-table-column>
              <el-table-column label="功率" prop="power"></el-table-column>
              <!-- <el-table-column label="等级" prop="grade"></el-table-column> -->
              <el-table-column label="小包号" prop="packName"></el-table-column>
              <el-table-column label="电池片数量" prop="packQty"></el-table-column>
              <el-table-column label="小包产出时间" prop="packTime1"></el-table-column>
              <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteBatchSave(scope.row)">删除</el-button>
                </template>
              </el-table-column>
              <div slot="empty">暂无数据,可直接根据当前表头建Excel,ctrl+c复制数据,然后ctrl+v黏贴此处!</div>
            </el-table>
          </div>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import {
    retraceResultList,
    listAResult,
    getAResult,
    delAResult,
    addAResult,
    updateAResult,
    createResult,
    routeList,
    getWorkOrderRestQty
  } from "@/api/system/aResult";
  import {
    listWorkorder
  } from "@/api/system/workorder";

  export default {
    name: "AResultSave",
    data() {
      return {
        activeName: 'oneCreate',
        // 遮罩层
        loading: true,
        fullscreenLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 追溯结果表格数据
        aResultList: [],
        batchSaveList: [],
        routeOptions: [],
        workOrderOptions: [],
        daterangePackTime: [],
        workOrderRestQty: 0,
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        openBatchSave: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          routeId: null,
          routeName: null,
          trackInTime: null,
          packName: null
        },
        // 表单参数
        form: {
          routeId: null,
          packQty: null,
          beginPackTime: null,
          endPackTime: null
        },
        // 表单校验
        rules: {
          routeId: [
            { required: true, message: "工艺路线不能为空", trigger: "change" }
          ],
        },
        columns: [],
      };
    },
    watch: {
      activeName(newVal, oldVal) {
        this.tabChange(newVal);
      }
    },
    created() {
      routeList().then(response => {
        this.routeOptions = response.data;
        if (this.routeOptions && this.routeOptions.length > 0) {
          this.queryParams.routeId = this.routeOptions[0].routeId;
          this.getList();
        }
      });
      this.initOneBatchSaveList();
      this.getWorkOrderOptions();
    },
    methods: {
      getColumnsFromData(data) {
        const columns = [];
        if (data.length > 0) {
          const keys = Object.keys(data[0]); // 获取第一个对象的所有键名
          keys.forEach(key => {
            columns.push({
              label: key, // 列标题
              prop: key, // 绑定到数据的属性名
              sortable: false // 是否可排序，根据需要设置
            });
          });
        }
        return columns;
      },
      /** 查询追溯结果列表 */
      getList() {
        this.loading = true;
        retraceResultList(this.queryParams).then(response => {
          this.aResultList = response.rows;
          this.columns = this.getColumnsFromData(this.aResultList);
          this.total = response.total;
          this.loading = false;
        });
      },
      /** 查询追溯结果列表 */
      getWorkOrderOptions() {
        let data = {
          pageNum: 1,
          pageSize: 100000,
          state: 'open'
        };
        listWorkorder(data).then(response => {
          this.workOrderOptions = response.rows;
        });
      },
      /** 工单选择 */
      productionOrderChange(e) {
        if (!e) {
          this.workOrderRestQty = 0;
        }
        getWorkOrderRestQty(e).then(response => {
          this.workOrderRestQty = response.data;
        });
      },
      /** 小包号转英文逗号 */
      handlePackNameConvert() {
        this.batchSaveList[0].packName = this.batchSaveList[0].packName.replace(/，/g, ',');
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 下载模板按钮操作 */
      downloadBatchSaveTemplate() {
        this.download('system/aResult/downloadRetraceResultTemplate', {
          ...this.queryParams
        }, `批次生成维护模板_${new Date().getTime()}.xlsx`)
      },
      tabChange(e) {
        this.form = {
          routeId: null,
          packQty: null,
          beginPackTime: null,
          endPackTime: null
        };
        this.resetForm("form");
        this.batchSaveList = [];
        this.daterangePackTime = [];
        if ("oneCreate" == e) {
          this.initOneBatchSaveList();
        }
      },
      initOneBatchSaveList() {
        var obj = {
          productionOrder: "",
          inBatchNo: "",
          palletNo: "",
          boxNo: "",
          efficiency: "",
          // color: "",
          pressure: "",
          power: "",
          // grade: "",
          packName: "",
          packQty: "",
          packTime1: ""
        };
        this.batchSaveList.push(obj);
      },
      handlePasteBatchSave(event) {
        this.batchSaveList = [];
        var clipdata = event.clipboardData || window.clipboardData;
        let content = clipdata.getData("text/plain");
        var data = [];
        if (content.indexOf("\r\n") > -1) {
          data = content.split('\r\n');
        } else {
          data = content.split('\n');
        }
        if (data.length > 1000) {
          this.$modal.msgError("黏贴数据不能大于1000行");
          return false;
        }
        for (let text of data) {
          if (!text) continue;
          var obj = {
            productionOrder: "",
            inBatchNo: "",
            palletNo: "",
            boxNo: "",
            efficiency: "",
            // color: "",
            pressure: "",
            power: "",
            // grade: "",
            packName: "",
            packQty: "",
            packTime1: ""
          };
          let arr = text.split('\t');
          let i = 0;
          for (var key in obj) {
            obj[key] = arr[i];
            i++;
          }
          this.batchSaveList.push(obj);
        }
      },
      cancelBatchSave() {
        this.openBatchSave = false;
        this.batchSaveList = [];
      },
      handleClearBatchSave() {
        this.batchSaveList = [];
      },
      rowPumpInfoIndex({row, rowIndex}) {
        row.index = rowIndex + 1;
      },
      handleDeleteBatchSave(row) {
        this.batchSaveList.splice(row.index - 1, 1);
      },
      validBatchSaveForm() {
        if (!this.batchSaveList) {
          this.$modal.msgError("上传数据不能为空！");
          return false;
        }
        if (null != this.form.packQty && '' != this.form.packQty && this.form.packQty <= 0) {
          this.$modal.msgError("主表小包数量不能小于等于0！");
          return false;
        }
        if ('oneCreate' == this.activeName) {
          if (!this.batchSaveList[0].productionOrder) {
            this.$modal.msgError("请输入工单号！");
            return false;
          }
          if (!this.batchSaveList[0].inBatchNo) {
            this.$modal.msgError("请输入入库批次！");
            return false;
          }
          if (!this.batchSaveList[0].palletNo) {
            this.$modal.msgError("请输入托号！");
            return false;
          }
          if (!this.batchSaveList[0].boxNo) {
            this.$modal.msgError("请输入箱号！");
            return false;
          }
          if (!this.batchSaveList[0].efficiency) {
            this.$modal.msgError("请输入效率！");
            return false;
          }
          if (!this.batchSaveList[0].pressure) {
            this.$modal.msgError("请输入开压！");
            return false;
          }
          if (!this.batchSaveList[0].power) {
            this.$modal.msgError("请输入功率！");
            return false;
          }
          if (!this.batchSaveList[0].packName) {
            this.$modal.msgError("请输入小包号！");
            return false;
          }
          if (!this.form.packQty) {
            this.$modal.msgError("请输入小包数量！");
            return false;
          }
          if (null == this.daterangePackTime || '' == this.daterangePackTime) {
            this.$modal.msgError("请选择入包时间！");
            return false;
          }
        } else {
          for (var i = 0; i < this.batchSaveList.length; i++) {
            if (!this.batchSaveList[i].packName) {
              this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包号不能为空！");
              return false;
            }
            if (this.batchSaveList[i].packQty && this.batchSaveList[i].packQty <= 0) {
              this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包数量不能小于等于0！");
              return false;
            }
            if (null != this.form.packQty && '' != this.form.packQty && this.batchSaveList[i].packQty) {
              this.$modal.msgError("主表已填写小包数量，明细表第" + this.batchSaveList[i].index + "项小包数量不能有值！");
              return false;
            }
            if ((null == this.form.packQty || '' == this.form.packQty) && !this.batchSaveList[i].packQty) {
              this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包数量不能为空！");
              return false;
            }
            if (null != this.daterangePackTime && '' != this.daterangePackTime && this.batchSaveList[i].packTime1) {
              this.$modal.msgError("主表已选择小包产出时间范围，明细表第" + this.batchSaveList[i].index + "项小包产出时间不能有值！");
              return false;
            }
            if ((null == this.daterangePackTime || '' == this.daterangePackTime) && !this.batchSaveList[i].packTime1) {
              this.$modal.msgError("第" + this.batchSaveList[i].index + "项小包产出时间不能为空！");
              return false;
            }
            if (!this.batchSaveList[i].productionOrder) {
              this.$modal.msgError("请输入工单号！");
              return false;
            }
            if (!this.batchSaveList[i].inBatchNo) {
              this.$modal.msgError("请输入入库批次！");
              return false;
            }
            if (!this.batchSaveList[i].palletNo) {
              this.$modal.msgError("请输入托号！");
              return false;
            }
            if (!this.batchSaveList[i].boxNo) {
              this.$modal.msgError("请输入箱号！");
              return false;
            }
            if (!this.batchSaveList[i].efficiency) {
              this.$modal.msgError("请输入效率！");
              return false;
            }
            if (!this.batchSaveList[i].pressure) {
              this.$modal.msgError("请输入开压！");
              return false;
            }
            if (!this.batchSaveList[i].power) {
              this.$modal.msgError("请输入功率！");
              return false;
            }
          }
        }
        return true;
      },
      submitBatchSaveForm() {
        this.fullscreenLoading = true;
        if (!this.validBatchSaveForm()) {
          this.fullscreenLoading = false;
          return;
        }
        this.form.beginPackTime = null;
        this.form.endPackTime = null;
        if (null != this.daterangePackTime && '' != this.daterangePackTime) {
          this.form.beginPackTime = this.daterangePackTime[0];
          this.form.endPackTime = this.daterangePackTime[1];
        }
        this.$refs["form"].validate(valid => {
          if (valid) {
            let data = {
              main: this.form,
              rows: this.batchSaveList
            };
            let bachSaveListOld ;
            let formold;
            if ('oneCreate' == this.activeName) {
              bachSaveListOld = this.batchSaveList;
              formold = this.form;
              console.log("formold=="+JSON.stringify(formold));
            }
            console.log("data22222=="+JSON.stringify(data));
            createResult(data).then(response => {
              this.$modal.msgSuccess(response.msg);
              this.openBatchSave = false;

               if ("oneCreate" == this.activeName) {
                this.batchSaveList = bachSaveListOld;
                this.form = formold;
                this.batchSaveList[0].packName = "";
              }else{
                this.tabChange(this.activeName);
              }

              console.log("formold000=="+JSON.stringify(formold));
              console.log("this.form11=="+JSON.stringify(this.form));
              this.getList();
              this.fullscreenLoading = false;
            }).catch(error => {
              this.fullscreenLoading = false;
            });
          } else {
            this.fullscreenLoading = false;
          }
        });
      },
    }
  };
</script>
